package org.custom.spring.boot.datasource.service.impl;

import org.custom.spring.boot.datasource.annotation.DatasourceSelection;
import org.custom.spring.boot.datasource.entity.StatementPropertity;
import org.custom.spring.boot.datasource.mapper.CustomMapper;
import org.custom.spring.boot.datasource.service.CustomService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 自定义SQL执行接口实现
 *
 * @author 李坤
 * @date 2022/3/31 19:33
 */
@Service("customService")
public class CustomServiceImpl implements CustomService {
    @Resource
    private CustomMapper customMapper;

    @Override
    public boolean validateSqlStatement(String metaSql) {
        return false;
    }

    @Override
    @DatasourceSelection
    public List<Map<String, Object>> executeCustomSql(StatementPropertity statementPropertity) {
        return customMapper.queryStatement(SqlPropertityUtil.assembleHashMap(statementPropertity));
    }

    /**
     * 静态内部类-用户自定义SQL相关操作工具类
     */
    public static class SqlPropertityUtil {
        /**
         * 将 sqlPropertity 组装为 Map 对象并返回
         *
         * @param statementPropertity 自定义SQL属性
         *
         * @return 组装后的数据
         */
        public static Map<String, Object> assembleHashMap(StatementPropertity statementPropertity) {
            Map<String, Object> params = statementPropertity.getParams();

            params.put("metaSql", statementPropertity.getMetaSql());

            return params;
        }
    }
}
